<script setup lang="ts">
import type { RenderContent } from '@arco-design/web-vue/es/_utils/types'
import { Message } from '@arco-design/web-vue'
import { deleteCertDomainApi, getCertDomainListApi } from '@/apis/modules/cert'
import { commonTableProps } from '@/utils/table'
import EditDialog from './components/EditDialog.vue'
import EditRemarkDialog from './components/EditRemarkDialog.vue'
import useConfig from './useConfig'

const { tableColumns, appList } = useConfig()

const queryParams = ref({ name_keyword: '' })

const { loading, data, run } = useListRequest(getCertDomainListApi, {
  params: queryParams,
  immediate: true,
})
const {
  visible: editDialogVisible,
  open: openEditDialog,
  data: editDialogData,
} = usePopup()
const {
  visible: editorRemarkDialogVisible,
  open: openEditorRemarkDialog,
  data: editorRemarkDialogData,
} = usePopup()

// 删除域名
function handleDelete(record: any) {
  ModalHelper.error({
    title: '删除域名',
    content: h('div', null, [
      '确定要删除 “',
      h('span', { class: 'text-[#FA5566]' }, `${record.name || '-'}`),
      '” 域名吗？',
    ]) as unknown as RenderContent,
    okText: '删除',
    width: 480,
    closable: false,
    onOk: async () => {
      await deleteCertDomainApi({ id: record.id })
      await run()
      Message.success('删除成功')
    },
  })
}

const { createSortChange } = useTable(run, data)
const onSorterChange = createSortChange(queryParams)
const hasAllApplication = computed(() => {
  // 是否已创建所有应用的域名
  // 获取data.value 中的所有app_id，并去重
  const appIds = Array.from(new Set(data.value?.map(item => item.app_id)))
  // 判断appIds的长度是否等于应用列表的长度，且每个应用都有对应的域名
  return (
    appIds.length === appList.value.length
    && appIds.every(id => data.value?.some(item => item.app_id === id))
  )
})

function shouldShowTooltip(remark: string) {
  if (!remark)
    return false
  return remark.length > 50 // 先按字符数快速判断
}
</script>

<template>
  <main-container
    :pagination="false"
    :loading="loading"
    @run="run"
  >
    <template #header>
      <div class="flex space-x-4">
        <a-tooltip
          content="所有应用均已添加域名"
          :class="{ hidden: !hasAllApplication }"
        >
          <a-button
            type="primary"
            :disabled="hasAllApplication"
            @click="openEditDialog()"
          >
            新建域名
          </a-button>
        </a-tooltip>
        <a-input-search
          v-model="queryParams.name_keyword"
          placeholder="请输入域名搜索"
          class="!w-58"
          allow-clear
          @search="run()"
          @clear="run()"
        />
      </div>
    </template>

    <a-table
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="data"
      @sorter-change="onSorterChange"
    >
      <template #appId="{ record }">
        {{ getOptionsLabel(appList, record.app_id) }}
      </template>
      <template #remark="{ record }">
        <div class="flex">
          <!-- <span
            style="
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            "
          >{{ record.remark || '-' }}</span> -->
          <a-tooltip
            :content="record.remark || '-'"
            position="top"
            :disabled="!shouldShowTooltip(record.remark)"
          >
            <span class="overflow-hidden text-ellipsis whitespace-nowrap">
              {{ record.remark || '-' }}
            </span>
          </a-tooltip>
          <div class="ml-1 min-w-4">
            <i-icons-edit
              class="table-icon"
              size="16px"
              @click="openEditorRemarkDialog(record)"
            />
          </div>
        </div>
      </template>
      <template #actions="{ record }">
        <a-link
          :hoverable="false"
          @click="openEditDialog(record)"
        >
          <i-icons-edit size="16px" />
        </a-link>
        <a-link
          :hoverable="false"
          status="danger"
          @click="handleDelete(record)"
        >
          <i-icons-delete size="16px" />
        </a-link>
      </template>
    </a-table>
  </main-container>
  <edit-dialog
    v-model:visible="editDialogVisible"
    :record="editDialogData"
    :list="data"
    @reload="run"
  />
  <edit-remark-dialog
    v-model:visible="editorRemarkDialogVisible"
    :record="editorRemarkDialogData"
    @reload="run"
  />
</template>

<style scoped>
:deep(.arco-table-tr) {
  .table-icon {
    opacity: 0;
    color: var(--color-text-7);
    cursor: pointer;
  }

  &:hover {
    .table-copy-text {
      @apply text-primary;
    }

    .table-icon {
      opacity: 1;
      color: #00a65b;
    }
  }
}
</style>
